<script setup lang="ts">
  import { UploadFileInfo, FormInst } from 'naive-ui'
  import {TOKEN_NAME, UPLOAD_IMG_SUPPORT, UPLOAD_IMG_PREFIX, SUCCESS_CODE} from '~/common/constants'
  // import { CheckmarkCircle } from '@vicons/ionicons5'
  const props = defineProps({
    draftId: {
      type: String,
      default: '',
      require: false
    },
    isArticle: {
      type: Boolean,
      default: false,
      require: false
    },
    option: {
      type: Object,
      default: () => {return {}},
      require: false
    },
    editorContent: {
      type: String,
      default: '',
      require: false
    }
  })
  // token 判断
  const token = useCookie(TOKEN_NAME)
  const tokenVal = token.value
  const nuxtApp = useNuxtApp()

  const rules = {
    categoryId: {
      required: true,
      // trigger: ['blur', 'change'],
      message: '请选择分类'
    },
    headImage: {
      required: true
    },
    tags: {
      type: 'array',
      required: true,
      trigger: 'change',
      message: '选择标签'
    },
    summary: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入摘要'
    }
  }
  const formRef = ref<FormInst | null>(null)
  const showPopover = ref(false)
  const publishData = ref({
      categoryId: '',
      headImage: '',
      summary: '',
      autholoyId: '',
      tags: []
  })
  const previewFileList = ref([])

  // get /index/tag // 获取标签列表
  // get /index/category // 获取文章分类列表
  // get /u/article // 获取登录用户相关文章
  // get /u/article/${id} 根据id获取要编辑到文章信息
  // get /u/authology 获取文集列表
  async function pushNote() {
    if (!props.draftId) {
      nuxtApp.$mutual['notification'].error({
        duration: 4000,
        content: '请传入草稿id' // nuxtApp.$i18n.t('common.tokenExpire')
      })
      return
    }
    if (!tokenVal) {
      if (process.client) {
        // const warnTokenText = getLangCommonData('tokenExpire')
        nuxtApp.$mutual.message.warning('令牌不存在或已过期，请重新登录', {
          duration: 4000
        })
      }
      navigateTo('/')
      return
    }
    const noteDataVal = publishData.value
    const warnText = props.draftId ? (noteDataVal.categoryId == 0 || noteDataVal.categoryId) ? noteDataVal.headImage || previewFileList.value.length ? noteDataVal.tags.length ? noteDataVal.summary ? '' : '请输入摘要' : '请选择标签' : '请选择封面图片' : '请选择分类' : '请传入草稿id'
    if (warnText) {
      nuxtApp.$mutual.message.warning(warnText, {
        duration: 4000
      })
    } else {
      const reqData = new FormData();
      reqData.append('categoryId', noteDataVal.categoryId)
      reqData.append('headImage', previewFileList.value[0].file || noteDataVal.headImage)
      reqData.append('summary', noteDataVal.summary)
      reqData.append('autholoyId', noteDataVal.autholoyId)
      reqData.append('tags', noteDataVal.tags)
      if (props.isArticle) {
        reqData.append('id', props.draftId)
        reqData.append('title', props.option.title || '')
        reqData.append('content', props.editorContent)
      } else {
        reqData.append('draftId', props.draftId)
      }
      const {data, msg, code} = await nuxtApp.$request('/u/article',{
        method: props.isArticle ? 'PUT': 'POST',
        server: false,
        key: props.isArticle ? 'changeArticle' : 'uArticle',
        body: reqData
      })
      if (code === SUCCESS_CODE) {
        nuxtApp.$mutual.message.success('发布成功！', {
          duration: 4000
        })
        navigateTo('/article')
      } else {
        nuxtApp.$mutual['message.vue'].error(msg, {
          duration: 4000
        })
      }
    }
  }
  function handlePreview (file: UploadFileInfo) {
    const { url } = file
    publishData.value.headImage = url as string
    // showModalRef.value = true
  }

  const categoryArr = ref([])
  const tagArr = ref([])
  const autholoyArr = ref([])

  nuxtApp.$request('/index/category',{
    method: 'GET',
    server: false,
    key: 'indexCategoryList'
  }).then(res => {
    categoryArr.value = res.data.map(item => {
      return {
        ...item,
        label: item.name,
        value: item.id
      }
    })
  })

  nuxtApp.$request('/index/tag',{
    method: 'GET',
    server: false,
    key: 'indexTagList'
  }).then(res => {
    tagArr.value = res.data.map(item => {
      return {
        ...item,
        checked: false
      }
    })
  })

  function getCollectionList() {
    nuxtApp.$request('/u/collection',{
      method: 'GET',
      server: false,
      key: 'uCollectionList'
    }).then(res => {
      autholoyArr.value = res.data.map(item => {
        return {
          ...item,
          label: item.name,
          value: item.id
        }
      })
    })
  }
  getCollectionList()
  function selectTag(item) {
    if (item.checked) {
      item.checked = !item.checked
    } else {
      if (tagArr.value.filter(i => i.checked).length < 3) {
        item.checked = !item.checked
      }
    }
    publishData.value.tags = tagArr.value.filter(i => i.checked).map(i => i.id)
  }
  function openPopover () {
    if (showPopover.value) {
      showPopover.value = false
      return
    }
    if (!props.draftId) {
      nuxtApp.$mutual.message.warning('请传入需要发布或更新的文章id', {
        // nuxtApp.$i18n.t('common.tokenExpire')
        duration: 3000
      })
    } else {
      if (props.option.title) {
        // todo 文章初始赋值(当前直接填写覆盖)
        // publishData.value = {
        //   categoryId: '',
        //   headImage: '', // (当前直接重新覆盖)
        //   summary: '',
        //   autholoyId: '',
        //   tags: []
        // }
      }
      showPopover.value = true
    }
  }
  function uploadLocal(e) {
    previewFileList.value = e.fileList
  }
  // function selectChange(e, type) {
  //   publishData.value[type] = e
  // }
</script>
<template>
  <n-popover :show="showPopover" width="530px" :title="props.isArticle ? '更新文章' : '发布文章'" trigger="click">
    <template #trigger>
      <n-button type="primary" @click="openPopover">
        {{props.isArticle ? '更新' : '发布'}}
      </n-button>
    </template>
    <n-form
      ref="formRef"
      :model="publishData"
      :rules="rules"
      label-placement="left"
      label-width="auto"
      require-mark-placement="right-hanging"
      size="medium"
      :style="{
      maxWidth: '100%'
    }"
    >
      <n-form-item label="分类" path="categoryId">
        <n-select
          v-model:value="publishData.categoryId"
          placeholder="选择文章分类"
          :options="categoryArr"
        />
<!--        @change="selectChange($event, 'categoryId')"-->
      </n-form-item>

      <n-form-item label="封面图" path="headImage">
        <n-upload
          :max="1"
          :default-upload="false"
          :default-file-list="previewFileList"
          list-type="image-card"
          @preview="handlePreview"
          @change="uploadLocal"
        />
      </n-form-item>
      <n-form-item label="标签" path="tags">
        <!--todo 标签选择-->
        <div>
          <n-tag class="tag-i" v-for="item in tagArr" :key="item.id" round :bordered="false" @click="selectTag(item)" :type="item.checked ? 'success':'default'">
            {{item.type}}
            <!--<template #icon>-->
            <!--<n-icon :component="CheckmarkCircle" />-->
            <!--</template>-->
          </n-tag>
        </div>
      </n-form-item>
      <n-form-item label="文集" path="autholoyId">
        <n-select
          style="flex: 1"
          v-model:value="publishData.autholoyId"
          placeholder="选择文集"
          :options="autholoyArr"
        />
<!--        @change="selectChange($event, 'autholoyId')"-->
        <ArticleCollectModal @change="getCollectionList"></ArticleCollectModal>
      </n-form-item>
      <n-form-item label="文章摘要" path="summary">
        <n-input
          v-model:value="publishData.summary"
          placeholder="文章摘要"
          type="textarea"
          :autosize="{
          minRows: 4,
          maxRows: 6
        }"
        />
      </n-form-item>
      <div style="display: flex; justify-content: flex-end">
        <!--取消-->
        <n-button round type="primary" @click="pushNote">
          确定{{props.isArticle ? '更新' : '发布'}}
        </n-button>
      </div>
    </n-form>
  </n-popover>
</template>
<style scoped lang="scss">
  .tag-i {
    margin-right: 8px;
    margin-bottom: 8px;
  }
</style>
